package cn.uniqueinfo.dp.aspect;

import cn.uniqueinfo.dp.annotation.NoRepeatSubmit;
import cn.uniqueinfo.dp.exception.UQException;
import com.google.common.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author:朱元勋
 * @mail:395910063@qq.com
 * @date:2019-01-09 20:25:53
 * @description: 防止重复提交注解
 */
@Aspect
@Component
@Slf4j
@Order(10)
public class NoRepeatSubmitAspect {

  @Autowired
  private Cache<String, Integer> cache;

  @Around("execution(* cn.uniqueinfo.dp.controller..*(..)) && @annotation(nrs)")
  public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit nrs) {
    log.debug("防止重复提交");
    try {
      ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
      HttpServletRequest request = attributes.getRequest();
      String key = sessionId + "-" + request.getServletPath();
      // 如果缓存中有这个url视为重复提交
      if (cache.getIfPresent(key) == null) {
        Object o = pjp.proceed();
        cache.put(key, 0);
        return o;
      } else {
        log.error("重复提交");
        return null;
        // throw new UQException(0,"NoRepeatSubmit","重复提交,请稍后再处理");
      }
    } catch (Throwable e) {
      e.printStackTrace();
      log.error("验证重复提交时出现未知异常!");
      // return "{\"code\":-889,\"message\":\"验证重复提交时出现未知异常!\"}";
      throw new UQException(0,"NoRepeatSubmit","验证重复提交时出现未知异常",e);
    }
  }
}
